package leetcode.剑指offer.前40;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/27 20:05
 * @description :https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
 */
public class 剑指_20_表示数值的字符串 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.isNumber("3e-10"));
    }

    class Solution {
        public boolean isNumber(String s) {
            s = s.trim();
            if (s.length() == 0) return false;
            if (isSignInt(s)) return true;
            if (isFloat(s)) return true;
            //判断是否为数值
            int index = Math.max(s.indexOf("e"), s.indexOf("E"));
            if (index == -1) return false;
            return (isFloat(s.substring(0, index)) || isSignInt(s.substring(0, index))) && isSignInt(s.substring(index + 1));
        }

        /**
         * 有符号整数
         * @param s
         * @return
         */
        private boolean isSignInt(String s) {
            if (s.length() == 0) return false;
            char[] chars = s.toCharArray();
            int i = 0;
            if (chars[i] == '+' || chars[i] == '-') i++;
            if (i >= s.length()) return false;
            for (;  i < chars.length; i++) {
                if (chars[i] < '0' || chars[i] > '9') return false;
            }
            return true;
        }

        /**
         * 无符号整数，主要用于小数点后数字判断
         * @param s
         * @return
         */
        private boolean isInt(String s) {
            if (s.length() == 0) return false;
            char[] chars = s.toCharArray();
            int i = 0;
            if (i >= s.length()) return false;
            for (;  i < chars.length; i++) {
                if (chars[i] < '0' || chars[i] > '9') return false;
            }
            return true;
        }

        /**
         * 小数判断
         * @param s
         * @return
         */
        private boolean isFloat(String s) {
            if (s.length() == 0) return false;
            int index = s.indexOf(".");
            if (index == -1) return false;
            int i = 0;
            if (s.charAt(0) == '+' || s.charAt(0) == '-') i++;
            if (index == i) {
                return isInt(s.substring(index + 1));
            } else if (index == s.length() - 1){
                return isInt(s.substring(i, index));
            } else {
                return isInt(s.substring(i, index)) && isInt(s.substring(index + 1));
            }
        }
    }

}
